package com.example.demo.util;

import com.example.demo.exception.BussinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;

/**
 * 统一拦截异常
 *
 * @author wyx
 * @version v1.3
 * @date 2021/1/1/12
 * @since v8.0
 **/
@RestControllerAdvice
public class GlobalDefultExceptionHandler {

    /**
     * 处理参数异常，一般用于校验body参数
     *
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ReturnEntity handleValidationBodyException(MethodArgumentNotValidException e) {
        for (ObjectError s : e.getBindingResult().getAllErrors()) {
            return new ReturnEntity("Invalid_Request_Parameter", s.getObjectName() + ": " + s.getDefaultMessage(), LocalDateTime.now().toString());
        }
        return new ReturnEntity("Invalid_Request_Parameter", "未知参数错误", LocalDateTime.now().toString());
    }

    /**
     * 日志
     */
    private static final Logger log = LoggerFactory.getLogger(GlobalDefultExceptionHandler.class);


    /**
     * 业务异常
     *
     * @param e
     * @param response
     * @return
     */
    @ExceptionHandler(BussinessException.class)
    public ReturnEntity handleUnProccessableBussinessException(ServiceException e, HttpServletResponse response) {
        response.setStatus(e.getStatusCode().value());
        return new ReturnEntity(e.getErrorCode(), e.getMessage(), LocalDateTime.now().toString());
    }

    /**
     * 主动throw的异常
     *
     * @param e
     * @param response
     * @return
     */
    @ExceptionHandler(ServiceException.class)
    public ReturnEntity handleUnProccessableServiceException(ServiceException e, HttpServletResponse response) {
        response.setStatus(e.getStatusCode().value());
        return new ReturnEntity(e.getErrorCode(), e.getMessage(), LocalDateTime.now().toString());
    }

    /**
     * 系统异常
     * Exception 异常类型 （写自己要拦截的异常类）
     * Result  自己封装的返回结果对象（可根据自己的方式修改返回结果）
     */
    @ExceptionHandler(Exception.class)
    public ReturnEntity handleException(Exception e) {
        //打印异常信息
        log.error(e.getMessage(), e);
        // 统一返回给前台页面信息（具体什么信息可以自己写）
        return new ReturnEntity("500", "服务器错误，请联系管理员", LocalDateTime.now().toString());
    }
}